package com.dev.itb.controller;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.dev.itb.domain.Person;
import com.dev.itb.service.SMCService;

@Controller
public class Itb001Controller {

	@Autowired
	SMCService smcService;

	@RequestMapping(value = "itb001.htm", method = RequestMethod.GET)
	public String init() {

//		System.out.println("status : " + smcService.getStatus());
		
		return "itb001";
	}

	@RequestMapping(value = "itb001.htm", method = RequestMethod.GET, params = { "xaction=view" })
	public ModelAndView view() {
		ModelAndView modelAndView = new ModelAndView("itb001");

		if(smcService.getStatus()){
			Person p = smcService.getPerson();
			System.out.println( p );
			modelAndView.addObject("person", p);
		}

		return modelAndView;
	}
	@RequestMapping(value = "itb001.htm", method = RequestMethod.GET, params = { "xaction=json" })
	public ModelAndView json() {
		ModelAndView modelAndView = new ModelAndView("itb001");
		
		if(smcService.getStatus()){
			Person p = smcService.getPerson();
				String string = toJson(p);
				System.out.println();
			    modelAndView.addObject("json", string);
		}else{
		        modelAndView.addObject("json", "{'error' : 'no data'}");
		}
		
		return modelAndView;
	}
	
	@RequestMapping(value = "itb001.htm", method = RequestMethod.POST, params = { "xaction=json" })
	public ModelAndView jsonPost() {
		return json();
	}
	
	public String toJson(Person p){
		Map<String, Object> person = new HashMap<String, Object>();
		person.put("firstNameThai", p.getFirstNameThai());
		person.put("lastNameThai", p.getLastNameThai());
		person.put("firstNameEng", p.getFirstNameEng());
		person.put("lastNameEng", p.getLastNameEng());
		person.put("preNameThai", p.getPreNameThai());
		person.put("preNameEng", p.getPreNameEng());
		person.put("age", p.getAge());
		person.put("birthDateStr", p.getBirthDateStr());
		person.put("expiredDateStr", p.getExpiredDateStr());
		person.put("sex", p.getSex());
		person.put("imageData", p.byteToString());
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("person", person);
		
		JSONObject jsonObject  = new JSONObject(root);
		
		return jsonObject.toString();
	}
}
